package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.RetailOutAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.base.BaseOriginal;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.OrderQueryParams;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.rOutappMain;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:  零售出库列表
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/6/28 13:48
 */
public class RetailOutListFragment extends BaseListFragment {

  private int REQUEST_ADD = 0;
  private int REQUEST_QUERY = 1;
  private ArrayList<rOutappMain> mlist;
  private String moutKindCode;
  private OrderQueryParams mQueryParams;
  private String moutbillNo;//出库单编号

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    setTitleCustom(mBaseParams.getName());
  }

  @Override public void initData() {
    super.initData();
    mlist = new ArrayList<>();
    moutKindCode = MyStringUtil.connect(mCurrentUser.getMemberCode(), mBaseParams.getCode());
    mQueryParams = new OrderQueryParams();
    mQueryParams.setBeginregDate(MyDateUtil.getFirstDay());
    mQueryParams.setEndregDate(MyDateUtil.getLastDay());
    mQueryParams.setDataStatusName(getString(R.string.all));
    mQueryParams.setFrom(RetailOutMainDetailFragment.ORDER == mBaseParams.getFrom()
        ? RetailInQueryFragment.RETAIL_ORDER
        : RetailInQueryFragment.RETAIL_OUT);//入库和出库使用同一个查询界面: 来自出库,如果是销售订单需显示客户名查询
    //获取出库单编码
    volleyGetCode();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_delegatetask, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

      case R.id.menu_item_add:
        //默认值
        rOutappMain content = new rOutappMain();
        content.setId(UUID.randomUUID().toString());
        content.setMemberCode(mCurrentUser.getMemberCode());
        content.setMoutappDate(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));
        content.setSumPrice(0.0);//出库类别编码
        content.setSumPriceString("零");//出库类别编码
        content.setIsOutAll("F");//出库类别编码
        content.setMoutkindCode(moutKindCode);//类型
        content.setMoutbillNo(moutbillNo);//出库单编号
        content.setMoutappmanName(mCurrentUser.getRealName());//申办业务员
        content.setMoutappmanId(mCurrentUser.getJobNumber());//申办业务员job
        content.setMoutappDate(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));//申办时间
        content.setMoutbillStatus(DataStatus.NEW);//数据状态
        content.setRegStaffName(mCurrentUser.getRealName());//登记人
        content.setRegStaffId(mCurrentUser.getJobNumber());
        content.setRegDate(MyDateUtil.format(new Date(), MyDateUtil.TYPE_DATE));//登记时间
        mBaseParams.setItem(content);
        mBaseParams.setType(BaseParams.TYPE_ADD);
        RetailOutDetailActivity.newInstance(this, RetailOutDetailActivity.class, mBaseParams,
            REQUEST_ADD);
        return true;
      case R.id.menu_item_search1:
        BaseVolleyActivity.newInstance(this, RetailInQueryActivity.class, mQueryParams,
            REQUEST_QUERY);
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Override public String getUrl() {
    return ApiConst.URL_OUT_MAIN_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("beginregDate", mQueryParams.getBeginregDate());
    String newEnd = MyDateUtil.getAfterDayTotring(mQueryParams.getEndregDate(), 1);
    params.put("endregDate", newEnd);
    params.put("moutbillStatus", mQueryParams.getDataStatus());
    params.put("customerName ", mQueryParams.getCustomerName());//客户名称,模糊查询
    params.put("moutkindCode", moutKindCode);
    params.put("orderField", "order_no");
    params.put("orderSeq", "desc");
    params.put("dataRange", "myData");//只能查出自己的销售订单
    return params.getParams();
  }

  @Override public void resolveResponse(String json) {

    BaseOriginal<rOutappMain> original =
        new Gson().fromJson(json, new TypeToken<BaseOriginal<rOutappMain>>() {
        }.getType());
    if (Base.SUCCESS == original.getResult() && original.getRows() != null) {
      mlist.clear();
      mlist.addAll(original.getRows());
      RetailOutAdapter madapter = new RetailOutAdapter(mActivity, mlist,
          RetailOutMainDetailFragment.ORDER == mBaseParams.getFrom() ? RetailOutAdapter.ORDER_SALE
              : RetailOutAdapter.RETAIL_OUT);
      setListAdapter(madapter);
    } else {
      ToastUtil.show("获取列表失败");
    }
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    rOutappMain outMain = mlist.get(position - 1);
    mBaseParams.setItem(outMain);
    mBaseParams.setType(BaseParams.TYPE_DETAIL);//详情
    RetailOutDetailActivity.newInstance(this, RetailOutDetailActivity.class, mBaseParams,
        REQUEST_ADD);
  }

  //获取单据编号
  private void volleyGetCode() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_ORDER_CODE);
    HashMap<String, String> params = new HashMap<>();
    params.put("memberCode", mCurrentUser.getMemberCode());
    params.put("ruleFlag", "outReceiptsRecordCode");
    params.put("certificateCode", moutKindCode);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            //获取单据编号成功
            moutbillNo = success.getMessage();
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(R.string.failure_operation);
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    //查询
    if (requestCode == REQUEST_QUERY) {
      mQueryParams = (OrderQueryParams) data.getSerializableExtra(BaseQueryFragment.EXTRA_PARAMS);
    }
    volleyPost();
    super.onActivityResult(requestCode, resultCode, data);
  }
}
